package com.zz.common.serialize;

import com.zz.common.enums.SerializationType;
import com.zz.common.exception.TunnelException;
import lombok.extern.slf4j.Slf4j;

/**
 * 序列化顶层抽象
 */
@Slf4j
public abstract class SubstrateDispatcher implements SerializerDispatcher {


    @Override
    public <T> byte[] serialize(byte serializationType, T obj) {
        try {
            return serialize(obj);
        } catch (Exception e) {
            log.error("序列化失败！error：{}, serializationType:{}",
                    e.getMessage(), SerializationType.getInstance(serializationType).getDesc());
            return new byte[0];
        }
    }

    @Override
    public <T> T deserialize(byte serializationType, byte[] data, Class<T> clazz) {
        try {
            return deserialize(data, clazz);
        } catch (Exception e) {
            log.error("反序列化失败！error:{}, serializationType:{}, clazz:{}",
                    e.getMessage(), SerializationType.getInstance(serializationType).getDesc(), clazz);
            try {
                return clazz.newInstance();
            } catch (Exception ex) {
                throw new TunnelException("通过反射创建对象失败");
            }
        }
    }

    public abstract <T> byte[] serialize(T obj) throws Exception;

    public abstract <T> T deserialize(byte[] data, Class<T> clazz) throws Exception;
}
